package controller

import (
	"gin/common/lib"
	"gin/common/lib/redis"
	"gin/middleware"
	"gin/model/body"
	captcha2 "gin/service/captcha"
	"gin/util/captcha"
	"gin/util/cryp"
	"gin/util/request"
	"gin/util/slider"
	"strings"

	error2 "gin/util/error"

	"github.com/gin-gonic/gin"
)

type CaptchaController struct {
}

func CaptchaRegister(router lib.RegisterRouterGroup, needLoginRouter lib.RegisterRouterGroup) {
	c := CaptchaController{}
	router.POST("/captcha/getCaptcha", c.getCaptcha)
	router.POST("/captcha/verifySlider", c.verifySlider)
}

// @Summary 获取验证码
func (*CaptchaController) getCaptcha(c *gin.Context) {
	var params struct {
		CaptchaType int64 `json:"captchaType"`
	}
	request.Bind(c, &params)

	ret := map[string]interface{}{}

	switch params.CaptchaType {
	case 1:
		// 图形验证码
		id, b64s, err := captcha.CaptMake(params.CaptchaType)
		ret["captchaId"] = id
		ret["captchaBase64"] = b64s
		if err != nil {
			error2.CustomPanic("获取验证码失败")
		}

	case 2, 3:
		// 手机，邮箱验证码

	case 4:
		// 滑块验证码
		jpBase64, jtBase64, rx, ry := slider.Generate()
		id := strings.Replace(cryp.GetUUID(), "-", "", -1)
		ret["sliderId"] = id
		ret["sliderBackground"] = jpBase64
		ret["silderGap"] = jtBase64
		ret["sliderY"] = ry

		redis.Set(redis.GetRedisKey("CAPTCHA", id), rx, 180)
	default:
	}
	middleware.Success(c, ret)
}

// @Summary 获取验证码配置
func (*CaptchaController) verifySlider(c *gin.Context) {
	var param body.CaptchaParam
	request.Bind(c, &param)
	captcha2.VerifySlider(param)
	middleware.Success(c)
}
